#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, String, Unicode
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""province_base collection has
    provid:            省会id(int）
    name:              城市名字拼音(string）
    cname:             城市名汉字(string）
"""

class ProvBaseItem(object):
    """docstring for ProvBaseItem"""

    def to_dict(self):
        res = {}
        res['provid'] = self.provid
        res['name'] = self.name
        res['cname'] = self.cname
        return res

    def __repr__(self):
        print "%d" % (self.provid)


prov_base_table = Table(
    'prov_base', metadata,
    Column('id', Integer, primary_key=True),
    Column('provid', Integer, index=True, nullable=False),
    Column('name', Unicode(65), nullable=False),
    Column('cname', Unicode(65), nullable=False)
)

mapper(ProvBaseItem, prov_base_table)


def create_prov_base_table_if_not_exist():
    metadata.create_all(engine)


def add_prov_base_item(p_item):
    item = ProvBaseItem()
    item.provid = p_item['provid']
    item.name = p_item['name']
    item.cname = p_item['cname']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True

    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_prov_base_by_provid(p_provid):
    try:
        session = Session()
        item = session.query(ProvBaseItem).filter_by(provid=p_provid).first()
        res = item.to_dict()
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_prov_base_by_provid_list(p_provid_list):
    try:
        session = Session()
        items = session.query(ProvBaseItem)\
            .filter(ProvBaseItem.provid.in_(p_provid_list)).all()
        res = [item.to_dict() for item in items]
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_all_prov_base():
    try:
        session = Session()
        items = session.query(ProvBaseItem).all()
        res = [item.to_dict() for item in items]
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def init_prov_data():
    """
    初始化数据，会删掉老数据，慎用
    :return:
    """
    prov_data = [
        (0, '公共', 'common'),
        (11, '北京', 'beijing'),
        (12, '天津', 'tianjin'),
        (31, '河北', 'hebei'),
        (14, '山西', 'shanxi'),
        (15, '内蒙古', 'neimenggu'),
        (21, '辽宁', 'liaoning'),
        (22, '吉林', 'jilin'),
        (23, '黑龙江', 'heilongjiang'),
        (31, '上海', 'shanghai'),
        (32, '江苏', 'jiangsu'),
        (33, '浙江', 'zhejiang'),
        (34, '安徽', 'anhui'),
        (35, '福建', 'fujian'),
        (35, '江西', 'jiangxi'),
        (37, '山东', 'shandong'),
        (41, '河南', 'henan'),
        (42, '湖北', 'hubei'),
        (43, '湖南', 'hunan'),
        (44, '广东', 'guangdong'),
        (45, '广西', 'guangxi'),
        (46, '海南', 'hainan'),
        (50, '重庆', 'chongqing'),
        (51, '四川', 'sichuan'),
        (52, '贵州', 'guizhou'),
        (53, '云南', 'yunnan'),
        (54, '西藏', 'xizang'),
        (61, '陕西', 'shaanxi'),
        (62, '甘肃', 'gansu'),
        (63, '青海', 'qinghai'),
        (64, '宁夏', 'ningxia'),
        (65, '新疆', 'xinjiang'),
        (852, '香港', 'xianggang'),
        (853, '澳门', 'aomen'),
        (886, '台湾', 'taiwan'),
        (82, '韩国', 'hanguo'),
    ]

    try:
        session = Session()
        session.query(ProvBaseItem).delete()
        for prov in prov_data:
            item = ProvBaseItem()
            item.provid = prov[0]
            item.name = prov[2]
            item.cname = prov[1]
            session.add(item)

        session.flush()
        session.commit()
        return True

    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

if __name__ == "__main__":
    create_prov_base_table_if_not_exist()
    init_prov_data()
